<template>
    <section>
        <!--编辑表单start -->
        <el-form :model="editForm" label-width='220px' ref='editForm' class='add-form' :rules='editFormRules'>
            <el-row class='mt-10 row-padding'>
                <el-form-item label='广告名称' prop='name'>
                    <el-input v-model="editForm.name" class='input-middle'></el-input>
                </el-form-item>
                <el-form-item label='广告位置' prop='type'>
                    <el-select v-model="editForm.type" placeholder='请选择' class='input-middle' >
                        <el-option label='首页顶部banner' value='0'></el-option>
                        <el-option label='首页导航图标' value='1'></el-option>
                        <el-option label='首页图标下方广告' value='2'></el-option>
                        <el-option label='分类页广告' value='3'></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="editForm.type === '3'" label='选择分类' prop='to_category'>
                    <el-select v-model="editForm.to_category" placeholder="请选择">
                        <el-option
                                v-for="item in classifyOptions"
                                :key="item.category_id"
                                :label="item.category_name"
                                :value="item.category_id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label='开始时间' prop='start_date'>
                        <el-date-picker
                                v-model="editForm.start_date"
                                type="datetime"
                                placeholder="选择日期时间"
                                value-format='yyyy-MM-dd HH:mm:ss'>
                        </el-date-picker>
                </el-form-item>
                <el-form-item label='到期时间' prop='end_date'>
                    <el-date-picker
                            v-model="editForm.end_date"
                            type="datetime"
                            placeholder="选择日期时间"
                            value-format='yyyy-MM-dd HH:mm:ss'>
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="显示状态" prop="status">
                    <el-switch
                            v-model="editForm.status"
                            active-color="#3C9EFF"
                            inactive-color="#D8DCE7"
                            :active-value="1" :inactive-value="2" >
                    </el-switch>
                </el-form-item>
                <el-form-item label="排序值" prop="sort">
                    <el-input-number v-model='editForm.sort' :min="1" :max="256"></el-input-number>
                    <!--<el-input type="number" v-model="editClassifyForm.category_sort" placeholder="只能输入1到256之间的数字" :min="1" :max="256"></el-input>-->
                </el-form-item>
                <el-form-item label="品牌图片" prop="image_path">
                    <el-upload :action='uploadUrl' :multiple="false" :on-success="onEditUploadSuccess" ref="editUpload"
                               list-type="picture-card" :headers="fileHeader" accept="jpg,png" :showFileList="false"
                               :before-upload="beforeUpload">
                        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过1M</div>
                        <img :src="oldBrandPic" class="upload-brand-img" v-show="oldBrandPic"/>
                    </el-upload>
                </el-form-item>
                <el-form-item label='广告链接' prop="url">
                    <el-input v-model='editForm.url' class='input-middle'></el-input>
                </el-form-item>
                <el-form-item label='广告备注' prop="remark">
                    <el-input type='textarea' v-model='editForm.remark'></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type='primary' @click='editSubmit'>保存</el-button>
                    <el-button @click='$router.back(-1)'>取消</el-button>
                </el-form-item>
            </el-row>
        </el-form>
        <!--编辑表单end -->
    </section>
</template>

<script>
import utils from '../../common/js/util'
import { editAdvert, getAdvert, getCategoriesList, uploadAdvertImg } from '../../api/api';

export default {
  data () {
    return {
      fileHeader: {
        Authorization: `Bearer ${this.$store.state.token}`
      },
      classifyOptions: [],
      editForm: {
          ad_id: null,
          name: '',
          type: null,
          start_date: '',
          end_date: '',
          image_path: '',
          url: '',
          to_category: null,
          status: null,
          sort: null
      },
      editFormRules: {
          name: [{ required: true, message: '请广告名称' }],
          type: [{ required: true, message: '请输入广告位置' }],
          start_date: [{ required: true, message: '请输入开始时间' }],
          end_date: [{ required: true, message: '请输入结束时间' }],
          sort: [{ required: true, message: '请输入排序' }],
          image_path: [{ required: true, message: '请选择图片' }],
          url: [{ required: true, message: '请链接URL' }]
      },
      uploadUrl: uploadAdvertImg,
      start_date: '',
      end_date: '',
      oldBrandPic: '',
      addBrandPic: ''
    };
  },
  methods: {
    // 编辑
    editSubmit () {
      this.$refs['editForm'].validate(valid => {
        if (valid) {
            editAdvert(this.editForm).then(res => {
            if (parseInt(res.status) === 1) {
              this.$message({
                message: '提交成功',
                type: 'success'
              });
            } else {
              this.$alert('编辑失败', '失败', { type: 'error' });
            }
          });
        }
      });
    },
    getAdvert () {
        getAdvert(this.$route.params.id).then(res => {
            getCategoriesList().then((res) => {
                if (parseInt(res.status) === 1) {
                    this.classifyOptions = res.data
                }
            })
           this.oldBrandPic = res.data.full_image;
           this.editForm = Object.assign({}, res.data);
           this.editForm.type = this.editForm.type.toString()
           this.editForm.to_category = this.editForm.to_category.toString()
      });
    },
      // 上传文件验证
      beforeUpload (file) {
          if (file.size > 1024 * 1000) {
              this.$alert('图片大小必须小于1M', '错误', {type: 'error'})
              return false;
          }
          if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
              this.$alert('图片格式必须是PNG,JPG', '错误', {type: 'error'});
              return false;
          }
      },
      // 上传文件成功钩子
      onUploadSuccess (response) {
          if (parseInt(response.status) === 1) {
              this.editForm.image_path = response.data.path;
              this.addBrandPic = response.data.fullUrl;
              this.$refs.editForm.validateField('image_path');
          } else {
              this.$alert('服务器保存文件失败,请重新上传', '错误', {type: 'error'});
          }
      },
      // 编辑上传钩子
      onEditUploadSuccess (response) {
          if (parseInt(response.status) === 1) {
              this.editForm.image_path = response.data.path;
              this.oldBrandPic = response.data.fullUrl;
          } else {
              this.$alert('服务器保存文件失败,请重新上传', '错误', {type: 'error'});
          }
      }
  },
  mounted () {
    this.getAdvert()
  }
};
</script>
<style rel='stylesheet/sass' lang='sass' scoped>
    $inputWidth: 300px
    .upload-success
        text-align: center
        vertical-align: middle
        div
            display: inline-block
            width: 100px

    .form-title
        margin: 20px 0
        padding-bottom: 5px
        font-size: 18px
        border-bottom: 1px solid #DFE4ED

    .button-div
        padding-bottom: 200px
        text-align: right
        margin-top: 30px
        button
            width: 100px
            margin-left: 20px

    .row-padding
        padding: 0 20px 20px 80px

    hr
        border-style: dashed
        border-color: #DFE4ED

    .input-middle
        width: $inputWidth

    .mt-10
        margin-top: 10px

    .mb-20
        margin-bottom: 20px

    .center
        text-align: center
    .upload-brand-img
        position: absolute
        left: 0
        width: 148px
        height: 148px
        background-color: #fbfdff
        border: 1px dashed #c0ccda
        border-radius: 6px
</style>